package com.iOS.util;

import net.coobird.thumbnailator.Thumbnails;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import static com.iOS.util.PathUtil.getImgBasePath;

/**
*@Author:WenTao
*@Description:图片处理文件类
*@Date:14:41 2018/9/20
*/
public class ImageUtil {
    private static final Random r = new Random();
    private static final SimpleDateFormat sDateFormate = new SimpleDateFormat("yyyyMMddHHmmss");
    /*图片处理,返回图片存储路径*/
    public static String ThumbnailsImg(InputStream ImgInputStream, String fileName, String targetAddr) {
        /*获取文件拓展名*/
        String extension = getFileExtension(fileName);

        /*获取保存到服务器后的文件名*/
        String realFileName = getRandomFileName();

        /*创建目录*/
        makeDirPath(targetAddr);

        /*绝对路径*/
        String relativeAddr = targetAddr + realFileName + extension;

        /*建立图片文件*/
        File dest = new File(relativeAddr);

        try{
            /*修改图片大小并存储*/
            Thumbnails.of(ImgInputStream)
                    .size(200,200)
                    .toFile(relativeAddr);
        }catch (IOException e){
            e.printStackTrace();
        }
        return relativeAddr;
    }

    /*获取输入文件流拓展名*/
    private static String getFileExtension(String fileName){
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /*生成新文件名**/
    private static String getRandomFileName(){
        /*当前修改时间加四位随机数*/
        int rannum = r.nextInt(8999) + 1000;
        String nowTimeStr = sDateFormate.format(new Date());
        return nowTimeStr + rannum;
    }

    /*创建目标路径所涉及的目录*/
    private static void makeDirPath(String targetAddr){
        String realFileParentPath =targetAddr;
        File dirPath = new File(realFileParentPath);
        if (!dirPath.exists()){
            dirPath.mkdirs();
        }
    }
}
